package langchain4j.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import langchain4j.bean.Appointment;
import langchain4j.mapper.AppointmentMapper;
import langchain4j.service.AppointmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Slf4j
@Service
public class AppointmentServiceImpl extends ServiceImpl<AppointmentMapper, Appointment> implements AppointmentService {

    @Autowired
    private AppointmentMapper mapper;
    /**
     * 查询订单是否存在
     * @param appointment
     * @return
     */
    @Override
    public Appointment getOne(Appointment appointment) {
        LambdaQueryWrapper<Appointment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Appointment::getUsername, appointment.getUsername());
        queryWrapper.eq(Appointment::getUserId, appointment.getUserId());
        queryWrapper.eq(Appointment::getIdCard, appointment.getIdCard());
        queryWrapper.eq(Appointment::getDepartment, appointment.getDepartment());
        queryWrapper.eq(Appointment::getDate, appointment.getDate());
        queryWrapper.eq(Appointment::getTime, appointment.getTime());
        queryWrapper.eq(Appointment::getIsDelete, 0);

        Appointment appointmentDB = baseMapper.selectOne(queryWrapper);
        return appointmentDB;
    }

    @Override
    public List<Appointment> listByUserId(Long userId) {
        LambdaQueryWrapper<Appointment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Appointment::getUserId,userId)
                .eq(Appointment::getIsDelete,0);
        return mapper.selectList(queryWrapper);
    }

    @Override
    @Transactional
    public boolean cancelAddAppointment(Integer id) {
        try {
            // 1. 构建更新条件
            LambdaUpdateWrapper<Appointment> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Appointment::getId, id)
                    .set(Appointment::getStatus, "cancelled");

            // 2. 执行更新
            boolean updated = update(updateWrapper);

            return updated;
        } catch (Exception e) {
            log.error("取消预约[{}]时发生异常: {}", id, e.getMessage());
            throw new RuntimeException("取消预约失败", e);
        }
    }
}